package com.ayuku.commons;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import net.sf.persist.Persist;

public class AyukuDB {
	private static Connection conn;
	private static Properties props;
	private static String jdbcString;
	private static int n = 0;
	private static Persist prsist;

	public static void openDB() throws InstantiationException,
			IllegalAccessException, ClassNotFoundException,
			FileNotFoundException, IOException, SQLException {
		Class.forName("org.h2.Driver").newInstance();
		setProp();
		prsist = new Persist(getConn());
	}

	private static void setProp() throws FileNotFoundException, IOException {
		// Application 1:
		// DriverManager.getConnection("jdbc:h2:/data/test;AUTO_SERVER=TRUE");

		// Application 2:
		// DriverManager.getConnection("jdbc:h2:/data/test;AUTO_SERVER=TRUE");

		Properties appSettings = new Properties();
		String mode = "single";
		String host = "localhost";
		String port = "8090";
		String user = "sa";
		try {
			appSettings.load(new FileInputStream("server.ini"));
			mode = appSettings.getProperty("mode", "single");
			host = appSettings.getProperty("host", "localhost");
			port = appSettings.getProperty("port", "8090");
		} catch (Exception e) {

		}

		char[] pwd = {};

		if ("single".equalsIgnoreCase(mode)) {
			jdbcString = "jdbc:h2:./db/course/aycourse;IFEXISTS=TRUE;AUTO_SERVER=TRUE";
			System.out.println("Connect to standalone db success....");
		} else if ("dev".equalsIgnoreCase(mode)) {
			jdbcString = "jdbc:h2:tcp://localhost/data/course/aycourse";
			System.out.println("Connect to dev db success....");
		} else {
			jdbcString = "jdbc:h2:tcp://" + host + ":" + port
					+ "/data/course/aycourse";
			System.out.println("Connect to server db success....");
		}

		props = new Properties();

		props.put("user", user);
		props.put("password", pwd);

	}

	public static Connection getConn() throws SQLException {
		if (conn == null || conn.isClosed()) {
			conn = DriverManager.getConnection(jdbcString, props);
			n += 1;
			System.out.println("connect lagi*** " + n);
		}
		conn.setAutoCommit(true);
		return conn;
	}

	public static void closeConn() throws java.sql.SQLException {
		conn.close();
	}

	public static Persist getPersist() throws SQLException {
		if (prsist == null || prsist.getConnection() == null
				|| prsist.getConnection().isClosed() || conn.isClosed()) {
			prsist = new Persist(getConn());
		}
		return prsist;
	}

}
